<?php

if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
	$db = new HocKy();
	$danhSachTieuChi = TieuChi::layDanhSachMaTieuChi($db);
	$thoiGian = new DateTime();
	$userPrefixNoDash = str_replace("_", "", $user->getPrefix());
	
	$insert = array(
				"HK_MA_SO" => $db->getMaHocKy(),
				$user->getPrefix() . 'MA_SO' => $user->getMaSo(),
				//'DIEM_' . $userPrefixNoDash => 0
				);
	
	if ($user->getPrefix() != "SV_")
		$insert['SV_MA_SO'] = intval($_GET['mssv']);
	
	$where = "";
	foreach ($insert as $key => $val) {
		if (is_string($val))
			$where .= "$key = '$val' AND ";
		else $where .= "$key = $val AND ";
	}
	 
	$insert['DIEM_' . $user->getPrefix() . 'THOI_GIAN'] = $thoiGian->format('Y-m-d H:i:s');
	$duplicate = 'DIEM_' . $user->getPrefix() . 'THOI_GIAN = \''
               . $thoiGian->format('Y-m-d H:i:s') . '\', DIEM_' . $userPrefixNoDash . ' = ';
	mysql_query("START TRANSACTION");
	$sumAll = 0;
	foreach($danhSachTieuChi as $maMuc => $data) {
		$sum = 0;
		foreach($data['DS_TIEU_CHI'] as $maTieuChi) {
			$result = $db->select("CHAM_DIEM_" . $userPrefixNoDash,
						  		  array("DIEM_" . $userPrefixNoDash . " as DIEM"),
						  		  $where . 'TC_MA_SO = ' . $maTieuChi);
			$diemCu = mysql_fetch_assoc($result);
			
			$diemTC = intval($_POST[$user->getPrefix() . 'Muc' . $maMuc . '_cboTC' . $maTieuChi]);
			$sum += $diemTC;
			
			//var_dump($diemCu);
			
			// if (chua ton tai) hoac (da ton tai va khac diem moi khac diem cu)
			if (!$diemCu || intval($diemCu['DIEM']) != $diemTC) {
				$insert['TC_MA_SO'] = $maTieuChi;
				$insert['DIEM_' . $userPrefixNoDash] = $diemTC;
				$db->insert("CHAM_DIEM_" . $userPrefixNoDash, $insert, $duplicate . $diemTC);
				$db->insert("LICH_SU_DIEM_" . $userPrefixNoDash, $insert);
			}
		}
		if ($sum > $data['DIEM_TOI_DA'])
			$sum = $data['DIEM_TOI_DA'];
		
		$sumAll += $sum;
	}
	
	$result = $db->select("BANG_DIEM_REN_LUYEN", array("BDRL_MA_SO"),
						  "BDRL_NGAY_AP_DUNG = (select max(BDRL_NGAY_AP_DUNG) "
						 . "from BANG_DIEM_REN_LUYEN)");
	$row = mysql_fetch_assoc($result);
	$maBangDRL = $row['BDRL_MA_SO'];
	
	$diemRenLuyen = array(
						'BDRL_MA_SO' => $maBangDRL,
						'HK_MA_SO' => $db->getMaHocKy(),
						'SV_MA_SO' => $insert['SV_MA_SO'],
						'TONG_DIEM_' . $userPrefixNoDash => $sumAll
						);
	
	$db->insert("CO_DIEM_REN_LUYEN", $diemRenLuyen,
				"TONG_DIEM_" . $userPrefixNoDash . " = " . $sumAll);
	
	$messageSuccess = "Chấm điểm thành công!";
	
	echo '<div class="message_success">' . $messageSuccess . '</div>';
	
	mysql_query("COMMIT");
}

if ($user->getPrefix() != "SV_") {
	include "views/ThongTinSinhVien.php";
}
else include "views/BangChamDiemRenLuyen.php";

?>